package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.WxCartService;
import com.cskaoyan.util.CurrentUesr;
import com.cskaoyan.util.MySystemUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: Fengyi
 * @description:
 * @time: 2021/7/12 17:14
 */
@Service
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    MallCartMapper mallCartMapper;
    @Autowired
    MallGoodsProductMapper mallGoodsProductMapper;
    @Autowired
    MallGoodsMapper mallGoodsMapper;
    @Autowired
    MallAddressMapper mallAddressMapper;
    @Autowired
    MallCouponMapper mallCouponMapper;
    @Autowired
    MallSystemMapper mallSystemMapper;
    @Autowired
    MySystemUtil mySystemUtil;

    @Override
    public WxCartIndexVO queryIndex() {
        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();

        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria criteria = mallCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        //todo shiro 获取malladmin

        criteria.andUserIdEqualTo(CurrentUesr.getUserId());


        List<MallCart> mallCarts = mallCartMapper.selectByExample(mallCartExample);
        wxCartIndexVO.setCartList(mallCarts);

        WxCartTotalVO wxCartTotalVO = new WxCartTotalVO();

        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        int CheckedGoodsCount = 0;
        BigDecimal GoodsAmount = new BigDecimal("0");
        int GoodsCount = 0;
        for (MallCart mallCart : mallCarts) {
            if (mallCart.getChecked()) {
                BigDecimal num = new BigDecimal(mallCart.getNumber().toString());
                BigDecimal price = mallCart.getPrice();
                BigDecimal multiply = price.multiply(num);
                checkedGoodsAmount = checkedGoodsAmount.add(multiply);
                CheckedGoodsCount += mallCart.getNumber();
            }
            BigDecimal num = new BigDecimal(mallCart.getNumber().toString());
            BigDecimal price = mallCart.getPrice();
            GoodsAmount = GoodsAmount.add(price.multiply(num));
            GoodsCount += mallCart.getNumber();

        }
        wxCartTotalVO.setCheckedGoodsAmount(checkedGoodsAmount);
        wxCartTotalVO.setCheckedGoodsCount(CheckedGoodsCount);
        wxCartTotalVO.setGoodsAmount(GoodsAmount);
        wxCartTotalVO.setGoodsCount(GoodsCount);

        wxCartIndexVO.setCartTotal(wxCartTotalVO);


        return wxCartIndexVO;
    }

    @Override
    public WxCartIndexVO checkedCart(WxCartCheckedBO wxCartCheckedBO) {

        //user_id
        int uid = CurrentUesr.getUserId();

        int isChecked = wxCartCheckedBO.getIsChecked();
        List<Integer> productIds = wxCartCheckedBO.getProductIds();
        for (Integer productId : productIds) {
            mallCartMapper.updateCheckedById(isChecked, productId, uid, new Date());
        }
        return queryIndex();
    }

    @Override
    public int updateCart(WxCartUpdateBO wxCartUpdateBO) {

        int hasCount = mallGoodsProductMapper.selectNumberByPid(wxCartUpdateBO.getProductId());

        if (hasCount < wxCartUpdateBO.getNumber()) {
            return 404;
        }

        mallCartMapper.updateNumberById(wxCartUpdateBO, new Date());
        return 200;
    }

    @Override
    public int goodsCount() {

        WxCartIndexVO wxCartIndexVO = new WxCartIndexVO();

        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria criteria = mallCartExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        //todo shiro 获取malladmin
        Subject subject = SecurityUtils.getSubject();
        MallUser user = (MallUser) subject.getPrincipals().getPrimaryPrincipal();

        criteria.andUserIdEqualTo(user.getId());

        List<MallCart> mallCarts = mallCartMapper.selectByExample(mallCartExample);
        wxCartIndexVO.setCartList(mallCarts);

        int GoodsCount = 0;
        for (MallCart mallCart : mallCarts) {

            GoodsCount += mallCart.getNumber();

        }


        return GoodsCount;
    }

    @Override
    public void deleteCartGoods(WxDeleteCartGoodsBO wxDeleteCartGoodsBO) {


        int userId = CurrentUesr.getUserId();
        Integer[] productIds = wxDeleteCartGoodsBO.getProductIds();
        for (Integer productId : productIds) {
            mallCartMapper.deleteById(userId, productId, new Date());
        }
    }

    @Override
    public int addGoodsToCart(WxAddGoodsToCartBO wxAddGoodsToCartBO) {
        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria cartExampleCriteria = mallCartExample.createCriteria();
        cartExampleCriteria.andDeletedEqualTo(false);
        //todo
        int uid = CurrentUesr.getUserId();
        cartExampleCriteria.andUserIdEqualTo(uid);

        //需要添加的数量
        short needNum = (short) wxAddGoodsToCartBO.getNumber();
        //判断库存 1 获取库存
        int hasCount = mallGoodsProductMapper.selectNumberByPid(wxAddGoodsToCartBO.getProductId());
        //2 获取旧值
        if (hasCount < needNum) {
            //库存不足，直接返回
            return 404;
        }


        int ifHas = mallCartMapper.selectNumByUidAndPid(wxAddGoodsToCartBO.getProductId(), uid);

        if (ifHas != 0) {
            //购物车里有这个商品
            Integer oldNum = mallCartMapper.selectOldNumByUidAndPid(wxAddGoodsToCartBO.getProductId(), uid);
            needNum += oldNum;
            if (hasCount < needNum) {
                //库存不足，直接返回
                return 404;
            }
            mallCartMapper.updateAddNumByUidAndPid(new Date(), needNum, wxAddGoodsToCartBO.getProductId(), uid);
            return 200;
        }


        MallGoodsExample mallGoodsExample = new MallGoodsExample();
        MallGoodsExample.Criteria mallGoodsExampleCriteria = mallGoodsExample.createCriteria();
        mallGoodsExampleCriteria.andDeletedEqualTo(false);

        MallGoods mallGoods = mallGoodsMapper.selectByPrimaryKey(wxAddGoodsToCartBO.getGoodsId());


        MallGoodsProductExample mallGoodsProductExample = new MallGoodsProductExample();
        MallGoodsProductExample.Criteria goodsProductExampleCriteria = mallGoodsProductExample.createCriteria();
        goodsProductExampleCriteria.andDeletedEqualTo(false);

        MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(wxAddGoodsToCartBO.getProductId());

        Date date = new Date();

        MallCart mallCart = new MallCart(null, uid, wxAddGoodsToCartBO.getGoodsId(), mallGoods.getGoodsSn(), mallGoods.getName(), mallGoodsProduct.getId(), mallGoodsProduct.getPrice(), needNum, mallGoodsProduct.getSpecifications(), false, mallGoodsProduct.getUrl(), date, date, false);

        mallCartMapper.insertSelective(mallCart);

        return 200;
    }

    @Override
    public int fastAdd(WxAddGoodsToCartBO wxAddGoodsToCartBO) {
        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria cartExampleCriteria = mallCartExample.createCriteria();
        cartExampleCriteria.andDeletedEqualTo(false);
        //todo
        int uid = CurrentUesr.getUserId();
        cartExampleCriteria.andUserIdEqualTo(uid);


        //需要添加的数量
        short needNum = (short) wxAddGoodsToCartBO.getNumber();
        //判断库存 1 获取库存
        int hasCount = mallGoodsProductMapper.selectNumberByPid(wxAddGoodsToCartBO.getProductId());
        //2 获取旧值
        if (hasCount < needNum) {
            //库存不足，直接返回
            return -1;
        }


        int ifHas = mallCartMapper.selectNumByUidAndPid(wxAddGoodsToCartBO.getProductId(), uid);

        if (ifHas != 0) {
            //购物车里有这个商品
            int cartId = mallCartMapper.selectCartIdByUidAndPid(wxAddGoodsToCartBO.getProductId(), uid);
            if (hasCount < needNum) {
                //库存不足，直接返回
                return -1;
            }
            mallCartMapper.updateAddNumByUidAndPid(new Date(), needNum, wxAddGoodsToCartBO.getProductId(), uid);
            return cartId;
        }


        MallGoodsExample mallGoodsExample = new MallGoodsExample();
        MallGoodsExample.Criteria mallGoodsExampleCriteria = mallGoodsExample.createCriteria();
        mallGoodsExampleCriteria.andDeletedEqualTo(false);

        MallGoods mallGoods = mallGoodsMapper.selectByPrimaryKey(wxAddGoodsToCartBO.getGoodsId());


        MallGoodsProductExample mallGoodsProductExample = new MallGoodsProductExample();
        MallGoodsProductExample.Criteria goodsProductExampleCriteria = mallGoodsProductExample.createCriteria();
        goodsProductExampleCriteria.andDeletedEqualTo(false);

        MallGoodsProduct mallGoodsProduct = mallGoodsProductMapper.selectByPrimaryKey(wxAddGoodsToCartBO.getProductId());

        Date date = new Date();

        MallCart mallCart = new MallCart(null, uid, wxAddGoodsToCartBO.getGoodsId(), mallGoods.getGoodsSn(), mallGoods.getName(), mallGoodsProduct.getId(), mallGoodsProduct.getPrice(), needNum, mallGoodsProduct.getSpecifications(), true, mallGoodsProduct.getUrl(), date, date, false);


        mallCartMapper.insertSelective(mallCart);

        return mallCart.getId();

    }

    @Override
    public WxCheckOutVO checkOut(WxCheckedOutBO wxCheckedOutBO) {
        WxCheckOutVO wxCheckOutVO = new WxCheckOutVO();



        //setAddressId setCheckedAddress
        MallAddressExample mallAddressExample = new MallAddressExample();
        MallAddressExample.Criteria addressExampleCriteria = mallAddressExample.createCriteria();
        addressExampleCriteria.andDeletedEqualTo(false);
        MallAddress mallAddress = mallAddressMapper.selectByPrimaryKey(wxCheckedOutBO.getAddressId());

        wxCheckOutVO.setAddressId(wxCheckedOutBO.getAddressId());
        wxCheckOutVO.setCheckedAddress(mallAddress);

        //checkedGoodsList
        MallCartExample mallCartExample = new MallCartExample();
        MallCartExample.Criteria cartExampleCriteria = mallCartExample.createCriteria();
        cartExampleCriteria.andDeletedEqualTo(false);

        cartExampleCriteria.andUserIdEqualTo(CurrentUesr.getUserId());
        cartExampleCriteria.andCheckedEqualTo(true);
        List<MallCart> mallCarts = null;
        if(wxCheckedOutBO.getCartId() != 0) {
            cartExampleCriteria.andIdEqualTo(wxCheckedOutBO.getCartId());
            mallCarts = mallCartMapper.selectByExample(mallCartExample);
        }else {
            mallCarts = mallCartMapper.selectByExample(mallCartExample);
        }

        wxCheckOutVO.setCheckedGoodsList(mallCarts);


        //setCouponId setCouponPrice
        wxCheckOutVO.setCouponId(wxCheckedOutBO.getCouponId());

        if(wxCheckedOutBO.getCouponId() == 0 || wxCheckedOutBO.getCouponId()  == -1) {
            wxCheckOutVO.setCouponPrice(0);
        }else {
            BigDecimal CouponPrice  = mallCouponMapper.selectPricebyCouponId(wxCheckedOutBO.getCouponId());
            wxCheckOutVO.setCouponPrice(CouponPrice.doubleValue());
        }


        //goodsTotalPrice
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        for (MallCart mallCart : mallCarts) {
            if (mallCart.getChecked()) {
                BigDecimal num = new BigDecimal(mallCart.getNumber().toString());
                BigDecimal price = mallCart.getPrice();
                BigDecimal multiply = price.multiply(num);
                checkedGoodsAmount = checkedGoodsAmount.add(multiply);
            }
        }

        wxCheckOutVO.setGoodsTotalPrice(checkedGoodsAmount);


        //freightPrice
        //根据后台配置，修改运费
        Map<String, String> systemMap = mySystemUtil.systemMap();
        Double freightMin = Double.parseDouble(systemMap.get("cskaoyan_mall_express_freight_min"));
        Double value = Double.parseDouble(systemMap.get("cskaoyan_mall_express_freight_value"));
        if(checkedGoodsAmount.doubleValue() < freightMin){
            wxCheckOutVO.setFreightPrice(value);
        }else {
            wxCheckOutVO.setFreightPrice(0.0);
        }



        //orderTotalPrice
        BigDecimal orderTotalPrice = checkedGoodsAmount;
        orderTotalPrice = orderTotalPrice.add(new BigDecimal(wxCheckOutVO.getFreightPrice()));
        orderTotalPrice = orderTotalPrice.subtract(new BigDecimal(wxCheckOutVO.getCouponPrice()));
        if(orderTotalPrice.doubleValue() < 0) {
            orderTotalPrice = new BigDecimal(0);
        }

        wxCheckOutVO.setOrderTotalPrice(orderTotalPrice);
        //setActualPrice
        wxCheckOutVO.setActualPrice(orderTotalPrice);

        return wxCheckOutVO;
    }
}
